package com.victor.common.core.utils;

import org.apache.pdfbox.cos.COSName;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.pdmodel.PDPage;
import org.apache.pdfbox.pdmodel.PDPageContentStream;
import org.apache.pdfbox.pdmodel.PDResources;
import org.apache.pdfbox.pdmodel.graphics.image.LosslessFactory;
import org.apache.pdfbox.pdmodel.graphics.image.PDImageXObject;
import org.apache.pdfbox.rendering.PDFRenderer;

import java.io.File;

public class PdfCompressorUtil2 {

    public static boolean pdfCompressor2(String originalFile, String compressedFile, float f) {
        try {
            // 加载PDF文件
            File inputFile = new File(originalFile);
            PDDocument document = PDDocument.load(inputFile);

            // 创建一个新的PDF文档用于保存压缩后的文件
            PDDocument compressedDoc = new PDDocument();

            PDFRenderer pdfRenderer = new PDFRenderer(document);
            for (int i = 0; i < document.getNumberOfPages(); i++) {
                PDPage page = document.getPage(i);

                // 渲染页面为图像
                PDImageXObject image = LosslessFactory.createFromImage(compressedDoc, pdfRenderer.renderImage(i, f)); // 0.5表示压缩图像质量

                // 创建新的页面并插入压缩后的图像
                PDPage newPage = new PDPage(page.getMediaBox());
                compressedDoc.addPage(newPage);

                PDPageContentStream contentStream = new PDPageContentStream(compressedDoc, newPage);
                contentStream.drawImage(image, 0, 0, page.getMediaBox().getWidth(), page.getMediaBox().getHeight());
                contentStream.close();
            }

            // 保存压缩后的PDF文件
            compressedDoc.save(compressedFile);

            // 关闭文档
            document.close();
            compressedDoc.close();

            return true;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }

    public static void main(String[] args) {
        String originalFile = "/Users/caoyang/Documents/ZY/manage/logs/123.pdf";
        String compressedFile = "/Users/caoyang/Documents/ZY/manage/logs/567.pdf";
        float f =1.5f;
        pdfCompressor2(originalFile, compressedFile, f);

    }
}
